import React, { useState, useEffect } from 'react';
import { List, Card, Avatar, Spin, message, Button, Modal } from 'antd';
import apiService from '../services/apiService';
import { JsonViewer } from '@textea/json-viewer';

const MomentList = () => {
  const [moments, setMoments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [total, setTotal] = useState(0);
  const [selectedMoment, setSelectedMoment] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [commentLoading, setCommentLoading] = useState(false);
  const [commentData, setCommentData] = useState(null);

  const pageSize = 5;

  const fetchMoments = async (pageNum = 0) => {
    setLoading(true);
    try {
      const response = await apiService.getMomentList(pageNum, pageSize);
      if (response && response['[]']) {
        setMoments(response['[]']);
        if (response.total) {
          setTotal(response.total);
        }
      }
    } catch (error) {
      message.error('获取动态列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMoments();
  }, []);

  const handlePageChange = (page) => {
    const newPage = page - 1;
    setPage(newPage);
    fetchMoments(newPage);
  };

  const showComments = async (momentId) => {
    setSelectedMoment(momentId);
    setModalVisible(true);
    setCommentLoading(true);
    
    try {
      const response = await apiService.getMomentWithComments(momentId);
      setCommentData(response);
    } catch (error) {
      message.error('获取评论失败');
    } finally {
      setCommentLoading(false);
    }
  };

  // 解析JSON字符串为数组
  const parseJsonArray = (jsonStr) => {
    try {
      if (!jsonStr) return [];
      return JSON.parse(jsonStr);
    } catch (error) {
      return [];
    }
  };

  return (
    <div>
      <Card title="动态列表">
        <Spin spinning={loading}>
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              onChange: handlePageChange,
              current: page + 1,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false
            }}
            dataSource={moments}
            renderItem={item => (
              <List.Item
                key={item.Moment.id}
                actions={[
                  <Button 
                    type="link" 
                    onClick={() => showComments(item.Moment.id)}
                  >
                    查看评论
                  </Button>
                ]}
                extra={
                  parseJsonArray(item.Moment.pictureList).length > 0 && (
                    <img
                      width={272}
                      alt="动态图片"
                      src={parseJsonArray(item.Moment.pictureList)[0]}
                    />
                  )
                }
              >
                <List.Item.Meta
                  avatar={<Avatar src={item.User.head} />}
                  title={item.User.name}
                  description={new Date(item.Moment.date).toLocaleString()}
                />
                {item.Moment.content}
              </List.Item>
            )}
          />
        </Spin>
      </Card>

      <Modal
        title="动态详情及评论"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Spin spinning={commentLoading}>
          {commentData && (
            <JsonViewer 
              value={commentData} 
              rootName={false} 
              displayDataTypes={false}
              displaySize={false}
              defaultInspectDepth={1}
              theme="light"
            />
          )}
        </Spin>
      </Modal>
    </div>
  );
};

export default MomentList; 